import { AfterViewChecked, Component, Injector, ViewChild, OnInit } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';

import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { PrimengTableHelper } from 'shared/helpers/PrimengTableHelper';
import { UserServiceProxy, ApplyChangeStepUserDto, WorkflowServiceProxy, ApplyChangeMainDto, ApplyChangeDetailsDto, ApplyChangeInputDto, OutsouringServiceProxy, ApplyChangeServiceProxy } from '@shared/service-proxies/service-proxies';

import { SelectItem, SelectItemGroup } from 'primeng/api';

@Component({
  selector: 'CrucialOutsourcingApplyChangeCreate',
  templateUrl: './CrucialOutsourcingApplyChangeCreate.component.html',
  styleUrls: ['./CrucialOutsourcingApplyChangeCreate.component.css']
})
export class CrucialOutsourcingApplyChangeCreateComponent extends AppComponentBase implements OnInit {
  @ViewChild('createOrEditModal') modal: ModalDirective;
  @ViewChild('paginator') paginator: Paginator;
  @ViewChild('dataTable') dataTable: Table;
  @ViewChild('teskdataTable') teskdataTable: Table;
  // @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;
  filterText = '';
  selectedCar3: string;
  detailsprimengTableHelper: PrimengTableHelper;
  _applyChangeDetailsDto: ApplyChangeDetailsDto[];
  clonedOutsourcings: { [s: number]: ApplyChangeDetailsDto; } = {};
  _applyChangeMainDto: ApplyChangeMainDto = new ApplyChangeMainDto();
  stepusers: ApplyChangeStepUserDto;
  users: SelectItemGroup[];

  SupplierAyy: SelectItem[];

  selectApplyChangeDetailsDto: ApplyChangeDetailsDto[];
  index = 0;
  constructor(injector: Injector,
    private _applyChangeAppService: ApplyChangeServiceProxy,
    private _userService: UserServiceProxy,
    private _workflowService: WorkflowServiceProxy
  ) {
    super(injector);
    this.detailsprimengTableHelper = new PrimengTableHelper();
    this.stepusers = new ApplyChangeStepUserDto();
  }

  ngOnInit(): void {

    this.selectApplyChangeDetailsDto = new Array<ApplyChangeDetailsDto>();
    this._userService.getAllUserForDropDown().subscribe(resultdata => {
      console.log(resultdata);
      this.users = resultdata;
    });
  }

  show(): void {
    this.active = true;
    this.modal.show();
  }
  close(): void {
    this.active = false;
    this.modal.hide();
  }
  onShown(): void {

  }
  getTasks(event?: LazyLoadEvent) {
    if (this.primengTableHelper.shouldResetPaging(event)) {
      this.paginator.changePage(0);
      return;
    }
    this.primengTableHelper.showLoadingIndicator();
    this._applyChangeAppService.getOutsourcingFormChangeModelByCode(
      1,
      this.filterText,
      'Code',
      this.primengTableHelper.getMaxResultCount(this.paginator, event),
      this.primengTableHelper.getSkipCount(this.paginator, event)
    )
      .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
      .subscribe(result => {
        console.log(result);
        this.primengTableHelper.totalRecordsCount = result.totalCount;
        this.primengTableHelper.records = result.items;
        this.primengTableHelper.hideLoadingIndicator();
      });
  }

  //依据申请单获取任务
  SelectTask(record) {
    console.log(record);
    this._applyChangeMainDto.applyUnit = record.applyUnit;
    let _supplier = record.supplierUnit.split(',');
    this.SupplierAyy = new Array();
    _.forEach(_supplier, viewItem => {
      console.log(viewItem);
      this.SupplierAyy.push({ label: viewItem, value: viewItem });
    });
    this._applyChangeMainDto.supplierUnit = this.SupplierAyy[0].value;

    this._applyChangeMainDto.code = record.code;
    this._applyChangeAppService.getOutsourcingApplyChangeDetailByWorkFlowId(record.workflowId).subscribe(dto => {
      console.log(dto);
      this._applyChangeDetailsDto = dto;
      this.detailsprimengTableHelper.totalRecordsCount = dto.length;
      this.detailsprimengTableHelper.records = dto;
      this.detailsprimengTableHelper.hideLoadingIndicator();
    });

    this._applyChangeAppService.buildApplyChangeOrderCodeByOutsourcingCode(record.code).subscribe(code => {
      this._applyChangeMainDto.changedCode = code;
    });
    this.index = 1;
  }

  handleChange(e) {
    this.index = e.index;
  }


  onRowEditInit(quotationmodel: ApplyChangeDetailsDto) {
    console.log(quotationmodel);
    //quotationmodel.processingAmount = quotationmodel.outsouringAmount;
    this.clonedOutsourcings[quotationmodel.taskForModelId.toString()] = { ...quotationmodel };
  }

  onRowEditSave(quotationmodel: ApplyChangeDetailsDto) {
    console.log(quotationmodel);
    if (quotationmodel.changedAmount > 0) {
      delete this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];

      let _current = this.selectApplyChangeDetailsDto.find((element) => (element.taskForModelId == quotationmodel.taskForModelId));
      if (_current === undefined) {
        //quotationmodel.processingAmount = quotationmodel.outsouringAmount;
        this.selectApplyChangeDetailsDto.push(quotationmodel);
      } else {
        _current.changeRemark = quotationmodel.changeRemark;
        _current.changedAmount = quotationmodel.changedAmount;
        _current.currentOutsouringProgress = quotationmodel.currentOutsouringProgress;
      }

    } else {
      this.notify.info('变更后数量不能小于0');
    }
  }

  onRowEditCancel(quotationmodel: ApplyChangeDetailsDto, index: number) {
    console.log(this.clonedOutsourcings[quotationmodel.taskForModelId.toString()]);
    this._applyChangeDetailsDto[index] = this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];
    delete this._applyChangeDetailsDto[quotationmodel.taskForModelId];
  }

  save() {
    let input = new ApplyChangeInputDto();
    // tslint:disable-next-line: triple-equals

    input.workFlowName = '关键过程外包申请变更通知单';
    console.log(this.selectApplyChangeDetailsDto);
    if (this.selectApplyChangeDetailsDto.length === 0) {
      this.notify.info('请填写变更内容');
      this.saving = false;
      return;
    }

    //判断审批用户是否设置
    if (!this.stepusers.workshopManager) {
      this.notify.info('请选择申请单位经办人');
      this.saving = false;
      return;
    }
    if (!this.stepusers.workShopLeader) {
      this.notify.info('请选择申请单位主管领导');
      this.saving = false;
      return;
    }
    if (!this.stepusers.plannedProductionModelManager) {
      this.notify.info('请选择计划生产处型号主管');
      this.saving = false;
      return;
    }
    if (!this.stepusers.plannedProductionDirector) {
      this.notify.info('请选择计划生产处主管处长');
      this.saving = false;
      return;
    }

    input.stepUserDto = this.stepusers;
    input.applyChangeMainDto = this._applyChangeMainDto;
    input.applyChangeDetailsDtos = this.selectApplyChangeDetailsDto;
    this.saving = true;

    console.log(input);

    this._applyChangeAppService.createOrUpdateCrucialOutsourcingChange(input)
      .pipe(finalize(() => { this.saving = false; }))
      .subscribe(() => {
        this.close();
      });
  }

}
